import OSS from 'ali-oss'
import {getEndpoint} from './util'
import * as step from '@flow-step/step-toolkit'

class CustomError extends Error {
    constructor(msg: string) {
        super(msg)
    }
}
export const customErrorInstance = new CustomError(
    'An error occurred when download from OSS.'
)
export const authErrorInstance = new CustomError(
    'Access denied by authorizer policy for OSS.'
)

export async function get(
    objectKey: string,
    localPath: string,
    userName: string | undefined,
    password: string | undefined,
    token: string | undefined,
    bucketName: string
) {
    if (
        userName === undefined ||
        password === undefined ||
        token === undefined
    ) {
        step.error(
            'Access denied by authorizer policy, STS temp credentials for OSS are empty.'
        )
        throw authErrorInstance
    }
    let endpoint = await getEndpoint()
    const client = new OSS({
        endpoint: endpoint,
        accessKeyId: userName,
        accessKeySecret: password,
        bucket: bucketName,
        stsToken: token
    })

    try {
        const result = await client.get(objectKey, localPath)
        //console.log(result)
        step.info(
            `Download artifact from OSS, status:${result.res.status}, size:${result.res.size}, time:${result.res.rt}`
        )
    } catch (e) {
        throw customErrorInstance
    }
}
